package com.yzt.zhuju.network;

import android.text.TextUtils;
import android.util.Log;

import com.yzt.zhuju.BuildConfig;
import com.yzt.zhuju.R;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.main.ExitAppEvent;
import com.yzt.zhuju.manager.DomainManager;
import com.yzt.p_base.AppUtils;
import com.yzt.p_base.utils.LogDataUtils;
import com.yzt.p_base.utils.NetworkUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.plugin_network.excep.HttpErrorMsg;
import com.yzt.plugin_network.excep.HttpStatus;
import com.yzt.plugin_network.response.AresException;
import com.yzt.plugin_network.response.HttpResponse;

import java.net.UnknownHostException;

import retrofit2.HttpException;
import rx.Subscriber;

/**
 * author : bob
 * date   : 2022/11/29
 * desc   :
 */
public abstract class AresSubscriber<T> extends Subscriber<T> {

    private HttpResponse response;

    private String mApiName;

    public void setApiName(String apiName) {
        this.mApiName = apiName;
    }

    @Override
    public void onCompleted() {
        onFinallyEnd();
    }

    @Override
    public void onError(Throwable e) {

        LogDataUtils.e("PRETTY_LOGGER_ERROR", Log.getStackTraceString(e));
        //No address associated with hostname
        LogDataUtils.e("AresSubscriber-[" + mApiName + "]", e.toString());
        if (e instanceof AresException) {
            AresException exception = (AresException) e;
            response = exception.response;
            if (onErrorToast() && exception.status != 947 && response != null && !TextUtils.isEmpty(response.msg)) {
                ToastUtil.showMessage(response.msg);
            }
            LogDataUtils.e(" [" + mApiName + "]--------onError = 【" + response + "】");
            //由父类统一处理
            if (exception.status == HttpStatus.ResponseStatus.TOKEN_INVALID) {
                //登陆失效
                onError(exception.status, exception.info);
            } else {
                onError(exception.status, exception.info);
                onError(exception.status, exception.info, response);
            }
            onErrorCode(exception.status);
        } else if (e instanceof HttpException) {
            LogDataUtils.e("PRETTY_LOGGER_ERROR", "HttpException:" + e);
            int code = ((HttpException) e).code();
            LogDataUtils.e("PRETTY_LOGGER_ERROR", "HttpException:" + code + "\t\t" + e);
            String msg = HttpErrorMsg.getHttpErrorMessage(code, "");
            onError(code, msg);
        } else if (e instanceof retrofit2.adapter.rxjava.HttpException) {
            LogDataUtils.e("PRETTY_LOGGER_ERROR", "retrofit2:" + e);
            int code = ((retrofit2.adapter.rxjava.HttpException) e).code();
            String msg = HttpErrorMsg.getHttpErrorMessage(code, "");
            if (code == HttpStatus.ResponseStatus.TOKEN_NO) {

            } else {
                if (code != HttpStatus.HttpCode.REQUEST_FORBID) {
                    if (onSystemErrorToast()) {
                        ToastUtil.showMessage(msg);
                    }
                }
                onError(code, msg);
            }
            onErrorCode(code);
        } else if (e instanceof UnknownHostException) {
            LogDataUtils.e("PRETTY_LOGGER_ERROR", "UnknownHostException:" + e);
            String message =AppUtils.getContext().getString(R.string.request_server_failed);

            if (!BuildConfig.DEBUG) {
                message = "";
            }
            if (!NetworkUtils.isNetAvailable()) {
                message = AppUtils.getContext().getString(R.string.network_not_connected);
            }
            if (onSystemErrorToast()) {
                ToastUtil.showMessage(message);
            }
            if (!BuildConfig.DEBUG) {
                String domain = DomainManager.getInstance().getDomain();
                if (!TextUtils.isEmpty(domain)) {
                    HttpUrlManager.saveHttpUrl(domain);
                } else {
                    DomainManager.getInstance().init(true);
                }
            }
            onError(HttpStatus.UnknownCode.SERVER_CALL_ERROR, message);
            onError(HttpStatus.UnknownCode.SERVER_CALL_ERROR, message, response);
        } else {
            String message =AppUtils.getContext().getString(R.string.request_server_failed);
            if (!BuildConfig.DEBUG) {
                message = "";
            }
            if (!NetworkUtils.isNetAvailable()) {
                message = AppUtils.getContext().getString(R.string.network_not_connected);
            }
            if (onSystemErrorToast()) {
                ToastUtil.showMessage(message);
            }
            onError(HttpStatus.UnknownCode.UNKNOWN_ERROR, message);
            onError(HttpStatus.UnknownCode.UNKNOWN_ERROR, message, response);
        }
        onFinallyEnd();
    }

    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    protected abstract void onSuccess(T t);

    /**
     * 如果异常需要子类去处理，则重写这个方法。
     *
     * @param code 错误码
     * @param info 错误信息
     */
    protected void onError(int code, String info) {
    }

    protected void onError(int code, String info, HttpResponse<T> response) {
    }

    protected void onFinallyEnd() {

    }

    /**
     * 接口response报错提示
     */
    public boolean onErrorToast() {
        return true;
    }

    public boolean onSystemErrorToast() {
        return BuildConfig.DEBUG;
    }

    protected HttpResponse getResponse() {
        return response;
    }

    private void onErrorCode(int code) {
        switch (code) {
            //token过期、拒绝、禁止
            case HttpStatus.ResponseStatus.TOKEN_INVALID:
            case HttpStatus.HttpCode.REQUEST_REFUSE:
            case HttpStatus.HttpCode.REQUEST_FORBID:
                Log.i("gz-base", "logout::token失效");
                RxBus.getDefault().post(new ExitAppEvent());
                break;
            default:
                break;
        }
    }
}
